package com.igeekhome.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.igeekhome.dto.WaybillDto;
import com.igeekhome.mapper.ScanMapper;
import com.igeekhome.mapper.WOrderListMapper;
import com.igeekhome.mapper.WWaybillMapper;
import com.igeekhome.pojo.Scan;
import com.igeekhome.pojo.WOrderList;
import com.igeekhome.pojo.WWaybill;
import com.igeekhome.service.IFileUploadService;
import com.igeekhome.service.IOrderNumberListService;
import com.igeekhome.service.IWaybillService;
import com.igeekhome.util.BarcodeUtil;
import com.igeekhome.util.CommonUtil;
import com.igeekhome.util.ResultBean;
import com.igeekhome.util.TableResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * @author Romeo
 */
@Service("waybillService")
public class WaybillServiceImpl implements IWaybillService {
    @Autowired
    private WWaybillMapper wWaybillMapper;
    @Autowired
    private WOrderListMapper wOrderListMapper;
    @Autowired
    private ScanMapper scanMapper;
    @Autowired
    private IOrderNumberListService orderNumberListService;
    @Autowired
    private IFileUploadService fileUploadService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean add(WWaybill waybill, String sendProvince, String sendCity, String sendArea, String recipientProvince, String recipientCity, String recipientArea, String sending_power) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            waybill = waybillTowaybill(waybill, sendProvince, sendCity, sendArea, recipientProvince, recipientCity, recipientArea);
            WOrderList orderList = waybillToOrderList(waybill);
            Scan scan = waybillToScan(waybill, sending_power);
            // 提交运单数据
            wWaybillMapper.updateByPrimaryKeySelective(waybill);

            // 提交订单数据
            wOrderListMapper.insertSelective(orderList);

            // 提交扫描信息
            scanMapper.insertSelective(scan);

        } catch (Exception e) {
            e.printStackTrace();
            // 回滚到回滚点
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ResultBean.fail("数据提交失败,已回滚");
        }
        return ResultBean.success();
    }

    @Override
    public ResultBean addUrlUpLoad(Integer wid, String src, String fileName) {
        WWaybill waybill = new WWaybill().setWaybillId(wid).setUrl(src).setFileName(fileName);
        int update = wWaybillMapper.updateByPrimaryKeySelective(waybill);
        if (update > 0) {
            return ResultBean.success();
        }
        return ResultBean.fail("上传附件失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean insert(Integer nid) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            Long waybill_id = orderNumberListService.getWaybillNumber(nid);
            if (waybill_id != null) {
                // 将Long转换成Integer可能会抛出转换异常
                Integer waybillId = waybill_id.intValue();
                // 生成条形码文件
                File file = BarcodeUtil.generateFile(waybillId.toString(), "D:/Image/" + waybillId + ".png");
                // 存放入七牛云中
                String originalFilename = file.getName();
                FileInputStream inputStream = null ;
                try {
                    inputStream = new FileInputStream(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 返回详细路径
                String src = fileUploadService.uploadFile(inputStream,originalFilename);
                WWaybill waybill = new WWaybill().setWaybillId(waybillId).setBarcode(src);
                int insert = wWaybillMapper.insertSelective(waybill);
                if (insert > 0) {
                    // 调用存放运单号的方法
                    orderNumberListService.saveUseWaybill(nid, waybillId);
                    return ResultBean.build(0, "成功", waybillId);
                }
                return ResultBean.fail("插入失败");
            }
            return ResultBean.fail("编号规则已经使用完，请重新分配单号");

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);

            return ResultBean.fail("数据提交失败,已回滚");
        }
    }

    @Override
    public WaybillDto selectByWid(Integer wid, Integer nid) {
        List<WaybillDto> waybillDtos = wWaybillMapper.selectByCondition(new WaybillDto().setWaybillId(wid).setNetworkId(nid));
        if (waybillDtos != null && waybillDtos.size() > 0) {
            return waybillDtos.get(0);
        }
        return null;
    }
    
    /**
     * @Description 给运单查询页面返回数据
     * @Param [page, limit, waybillDto]
     * @Return com.igeekhome.util.TableResultBean
     **/
    @Override
    public TableResultBean waybillList(Integer page, Integer limit, WaybillDto waybillDto) {
        //开启分页
        PageHelper.startPage(page, limit);
      
        List<WaybillDto> waybillDtos = wWaybillMapper.selectByCondition(waybillDto);
        for (WaybillDto dto : waybillDtos) {
            //拆分寄件人详细地址
            String[] site1 = CommonUtil.addressToList(dto.getDetailedAddress());
            //拆分收件人详细地址
            String[] site2 = CommonUtil.addressToList(dto.getRecipientDetailedAddress());
            
            if (site1.length == 4) {
                dto.setProvince(site1[0]).setCity(site1[1]).setArea(site1[2]).setAddress(site1[3]);
            }
            
            if (site2.length == 4) {
                dto.setRecipientProvince(site2[0]).setRecipientCity(site2[1]).setRecipientArea(site2[2]).setRecipientAddress(site2[3]);
            }
            
        }
        
        //获取集合总条数
        long total = new PageInfo<WaybillDto>(waybillDtos).getTotal();
        
        return TableResultBean.ok(total, waybillDtos);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean delete(Integer waybillId) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        if (waybillId == null) {
            return ResultBean.fail("删除失败");
        }
        try {
            // 更新运单数据状态
            wWaybillMapper.updateStatusById(waybillId);
            
            // 更新订单数据状态
            wOrderListMapper.updateStatusByWaybilId(waybillId);
            
            // 更新扫描数据状态
            scanMapper.updateStatusByWaybillId(waybillId);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚到回滚点
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ResultBean.fail("数据提交失败,已回滚");
        }
        return ResultBean.success();
    }
    
    
    /**
     * @author 汪璇
     * @Description 修改运单信息
     * @Param [wWaybill]
     * @Return com.igeekhome.util.ResultBean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean update(Integer networkId,WWaybill wWaybill,String sendProvince,String sendCity,String sendArea,String address,String recipientProvince,String recipientCity,String recipientArea,String recipientAddress) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        
        wWaybill.setNetworkId(networkId);
        //拼接寄件人详细地址
        wWaybill.setDetailedAddress(sendProvince+","+sendCity+","+sendArea+","+address);
        //拼接收件人详细地址
        wWaybill.setRecipientDetailedAddress(recipientProvince+","+recipientCity+","+recipientArea+","+recipientAddress);
        if (wWaybill == null) {
            return ResultBean.fail("更新失败");
        }
        try {
            // 更新运单数据
            wWaybillMapper.updateByPrimaryKeySelective(wWaybill);
            
            // 更新订单数据
            WOrderList orderList = waybillToOrderList(wWaybill);
            wOrderListMapper.updateByWaybillIdSelective(orderList);
            
            // 更新扫描数据
            Scan scan = waybillToScan(wWaybill, null);
            scanMapper.updateByWaybillIdSelective(scan);
            
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚到回滚点
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            return ResultBean.fail("数据提交失败,已回滚");
        }
        return ResultBean.success();
    }
    
    private WWaybill waybillTowaybill(WWaybill waybill ,String sendProvince, String sendCity, String sendArea, String recipientProvince, String recipientCity, String recipientArea) {
        // 运单操作
        waybill.setStatus(1);
        // 详细地址操作
        waybill.setDetailedAddress(CommonUtil.toSplicing(sendProvince, sendCity, sendArea, waybill.getDetailedAddress()));
        waybill.setRecipientDetailedAddress(CommonUtil.toSplicing(recipientProvince, recipientCity, recipientArea, waybill.getRecipientDetailedAddress()));
        return waybill;
    }
    private WOrderList waybillToOrderList(WWaybill waybill){
        // 设置订单信息
        WOrderList orderList = new WOrderList().setCaseNumber(waybill.getNumber()).setWeight(waybill.getWeight()).setSender(waybill.getSenderName())
                .setSendTel(waybill.getSenderPhonenumber()).setSendAddress(waybill.getDetailedAddress()).setRemark(waybill.getRemarks()).setRecipients(waybill.getRecipient())
                .setReceiveTel(waybill.getRecipientPhonenumber()).setConsigneeAddress(waybill.getRecipientDetailedAddress()).setCatalogueState("1")
                .setWaybillId(waybill.getWaybillId()).setAssignBranchStaffId(waybill.getTakerId());
        return orderList;
    }
    private Scan waybillToScan(WWaybill waybill , String sending_power){
        // 设置扫描信息
        Scan scan = new Scan().setWaybillNumber(waybill.getWaybillId()).setScanType(",").setExpressTypeId(waybill.getExpressTypeId())
                .setItemTypeId(waybill.getItemTypeId()).setSenderClient(waybill.getSenderName()).setReceiver(waybill.getRecipient())
                .setTransportMethodId(waybill.getTransportMethodId()).setPaymentMethodId(waybill.getPaymentMethodId()).setSendNetworkId(waybill.getNetworkId())
                .setWeight(waybill.getWeight()).setTakerId(waybill.getTakerId()).setDestinationId(waybill.getDestinationId()).setStatus(1)
                .setDestinationNetworkId(waybill.getTransportNetworkId()).setScanNetworkId(waybill.getNetworkId());
                if (sending_power != null && sending_power.length() > 0) {
                    scan.setScanPower(sending_power);
                }
        return scan;
    }
    
}
